"""

作者:"F的工作室"

全网同名，感谢关注！

开发不易，求个star和点赞！

"""





from microdot import Microdot
import time
import camera
from machine import reset
import network

try:
    camera.init(0, format=camera.JPEG, fb_location=camera.PSRAM)
except OSError:
    camera.deinit()
    camera.init(0, format=camera.JPEG, fb_location=camera.PSRAM)

print("Camera ready")

def connect():
  wlan = network.WLAN(network.STA_IF)
  wlan.active(True)
  if not wlan.isconnected():
      print('connecting to network...')
      wlan.connect(SSID, PASSWORD)
      while not wlan.isconnected():
          pass
  print('network config: ', wlan.ifconfig())

connect()
app = Microdot()

    
@app.route('/')
def index(request):
    return '''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP32-CAM 视频监控</title>
    <style>
      body {
        font-family: '微软雅黑', '宋体', 'Helvetica Neue', Arial, sans-serif;
        background-color: #f4f4f4;
        color: #333;
        text-align: center;
        margin: 0;
        padding: 0;
      }
      h1 {
        color: #4CAF50;
      }
      .video-container {
        width: 60%;
        margin: 20px auto;
        box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
        border-radius: 10px;
        overflow: hidden;
      }
      .video-container img {
        width: 100%;
        height: auto;
        border-radius: 10px;
      }
    </style>
  </head>
  <body>
    <h1>ESP32-CAM 视频监控</h1>
    <div class="video-container">
      <img src="/video_feed" alt="Video Feed">
    </div>
  </body>
</html>
''', 200, {'Content-Type': 'text/html'}

@app.route('/video_feed')
def video_feed(request):
    def stream():
        yield b'--frame\r\n'
        while True:
            frame = camera.capture()
            yield b'Content-Type: image/jpeg\r\n\r\n' + frame + \
                b'\r\n--frame\r\n'

    return stream(), 200, {'Content-Type':
                           'multipart/x-mixed-replace; boundary=frame'}


if __name__ == '__main__':
    app.run(debug=True)
